import { ref, onUnmounted, readonly, reactive } from 'vue'

/*
*	倒计时定时器
*	@params {time} 倒计时时长
*/
function Timer(time, startTime = 0) {
	const initState = {
		time: startTime,
		isUsed: false
	}
	const state = reactive(initState)
	initState.timer = null
	const start = (callback) => {
		if(initState.time > 0) {
			return ;
		}
		state.time = time
		state.isUsed = true
		initState.timer = setInterval(() => {
			state.time --;
			if(state.time === startTime) {
				clearInterval(initState.timer)
			}
		}, 1000)
		callback && callback()
	}
	const reset = () => {
		clearInterval(initState.timer)
		state.time = startTime
	}
	onUnmounted(reset)
	initState.start = start
	initState.reset = reset
	return readonly(state)
}

export default Timer